const express = require("express");
const app = express();

const session = require("express-session");

// post数据接收配置
// $cnpm i body-parser -S
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// session配置
app.use(session({
    secret: "iloveyou",//验证data+key
    resave: false,//即使session 没有被修改 也保存session值
    saveUninitialized: true,//保存session数据到本地
}))

// ejs配置
const ejs = require('ejs');
app.engine('html', ejs.__express);
app.set('view engine', 'html');

// 引入静态资源
app.use(express.static("./assets"))

// 引入md5
const { md5 } = require("./function/md5");

// 引入数据库
// $cnpm i mysql -S
const DB = require("./function/mysql");

// 登录
app.get("/", (req, res) => {
    res.render("login");
    
})
// 注册
app.get("/register", (req, res) => {
    res.render("register")
})

// 登录数据
app.post("/loginPost", (req, res) => {
    console.log(req.body);
    // 后端在验证数据
    let { username, password } = req.body;

    var reg_username = /^[A-Za-z0-9\u4e00-\u9fa5]{2,10}$/;
    var reg_password = /^[a-zA-Z0-9]\w{5,17}$/
    if (!reg_username.test(username) || !reg_password.test(password)) {
        console.log("请输入正确数据");
        return;
    }

    // 明文密码==>密文密码
    password = md5(password);
    // console.log(password);

    // 请求数据库，验证用户名密码
    DB.exec({
        sql: `select * from user where username = ? and password = ?`,
        params: [username, password],
        callback(data) {
            console.log(data);
            if (data.length && "id" in data[0]) {
                console.log("登录成功");
                req.session.login = 1;//登录成功
                req.session.info = data[0]; //用户信息存session中
                res.redirect("/home");
            } else {
                console.log("登录失败");
            }
        }
    })

})

// 注册数据
app.post("/registerPost", (req, res) => {
    let { username, password, password2 } = req.body;
    var reg_username = /^[A-Za-z0-9\u4e00-\u9fa5]{2,10}$/;
    var reg_password = /^[a-zA-Z0-9]\w{5,17}$/
    if (!reg_username.test(username) || !reg_password.test(password) || password2 != password) {
        console.log("请输入正确数据");
        return;
    }
    console.log("开始注册数据");

    DB.exec({
        sql: `select * from user where username = ?`,
        params: [username],
        callback(data) {
            console.log(data);
            if (data.length && "id" in data[0]) {
                console.log("不允许注册");
                res.redirect("/register");

            } else {
                console.log("允许注册");

                password = md5(password);//密码加密
                DB.exec({
                    sql: `insert into user (username,password) values (?,?)`,
                    params: [username, password],
                    callback(data) {
                        res.redirect("/");//登录页面
                    }
                })
            }
        }
    })

})

// 过滤器
app.use((req, res, next) => {
    if (req.session.login === 1) { //登录成功==>跳出路由
        next();//跳出路由
    } else {
        res.redirect("/");
    }
})

// 必须登录后才可以进入页面
app.get("/home", (req, res) => {
    // res.render("home")
    // 请求数据
    DB.exec({
        sql: `select * from userinfo`,
        callback(data) {
            console.log(data);
            res.render("home", {
                datalists: data
            })
        }
    })
    // res.send(req.session.info.username + "==>首页home页面<a href='/clear'>退出登录</a>")
})

// 添加页面
app.get("/add", (req, res) => {
    res.render("add")
    // res.send(req.session.info.username + "==>首页home页面<a href='/clear'>退出登录</a>")
})
// 添加数据
app.get("/setData", (req, res) => {
    console.log(req.query);
    let { name, age, info } = req.query;
    DB.exec({
        sql: `insert into userinfo (name,age,info) values (?,?,?)`,
        params: [name, age, info],
        callback(data) {
            console.log(data);
            if (data.insertId) {//判断是否添加成功id值
                res.redirect("/home");//重定向首页
            }
        }
    })
})

// 修改页面
app.get("/edit", (req, res) => {
    let id = req.query.id;
    DB.exec({
        sql: `select * from userinfo where id = ${id}`,
        callback(data) {
            console.log("获取修改数据==>", data);
            res.render("edit", data[0])
        }
    })

})

// 修改数据
app.get("/setEdit", (req, res) => {
    let { id, name, age, info } = req.query;
    DB.exec({
        sql: `update userinfo set name="${name}",age="${age}",info="${info}" where id="${id}"`,
        callback(data) {
            // console.log("数据修改成功==>",data);
            res.redirect("/home");
        }
    })
})

// 删除数据
app.get("/del", (req, res) => {
    let id = req.query.id;//获取id值
    if (!id) {
        return;
    }
    DB.exec({
        sql: `delete from userinfo where id =?`,
        params: [id],
        callback() {
            res.redirect("/home");
        }
    })
})



// 退出登录
app.get("/clear", (req, res) => {
    req.session.login = null;//退出登录
    res.redirect("/");
})


app.listen(3000, () => {
    console.log("http://127.0.0.1:3000");
})